<?php

namespace App\Http\Controllers;

use App\Models\Column;
use App\Models\Database;
use App\Services\DBAPP;
use Facade\Ignition\Tabs\Tab;
use Illuminate\Http\Request;
use App\Services\Table;
use App\Models\Table as TableModel;

class TableController extends Controller
{
    public function index(Request $i) {
        $db = Database::default(TOKEN_USER);
        $tables = TableModel::db_tables($db->id);
        $tables ?: [];
        return $this->success($tables);
    }

    public function detail(Request $i) {

        $id = $i->input('id');
        $columns = TableModel::columns($id);
        return $this->success($columns);
    }

    public function create(Request $i) {
        $title      = $i->input('title');
        $name       = $i->input('name');
        $columns    = $i->input('columns');
        $columns    = json_decode(json_encode($columns), true);
        $db         = Database::default(TOKEN_USER);
        $res        = Table::create($db->id, $title, $name, $columns);
        if (!$res) {
            return $this->fail(Table::error());
        }
        return $this->success($res);
    }

    /**
     * @param Request $i
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $i) {
        $table = $i->input('table');
        $res = Table::update($table['id'], $table['name'], $table['title'], $table['columns']);
        if (!$res) {
            return $this->json(40000, Table::error());
        } else {
            return $this->json();
        }
    }

    /**
     * 删除数据表
     * @param Request $i
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $i) {
        $tableId = $i->input('id');
        // 检查这个表是否是用户自己的
        $tableInfo = TableModel::find($tableId);
        $dbInfo     = Database::find($tableInfo->db_id);
        if ($dbInfo->user_id != TOKEN_USER) {
            return $this->json(40000, '权限不足，非法操作！');
        }
        Table::drop($tableId);
        return $this->json();
    }

    public function deleteColumn(Request $i) {
        $columnId   = $i->input('id');
        $column     = Column::find($columnId);
        $tableInfo  = TableModel::find($column->table_id);
        $dbInfo     = Database::find($tableInfo->db_id);

        if ($dbInfo->user_id != TOKEN_USER) {
            return $this->json(40000, '权限不足，非法操作');
        }

        Table::dropColum($columnId);
        return $this->json();
    }
}
